import React from 'react';
import { Button, Tabs, Card, Tooltip, Row, Col, Spin, Menu, Icon  } from 'antd';
import { Condition, getAdButtons } from '../list/listCondition';
import { inject, observer } from 'mobx-react';
import { WeaTop, WeaInputSearch, WeaLeftRightLayout, WeaNewScroll, WeaTab , WeaRightMenu , WeaProgress, WeaDialog, WeaTools  } from 'ecCom';
import {routerShape} from 'react-router';
const { SubMenu } = Menu;
import AddTaskGroupDialog from '../dialog/addTaskGroupDialog';
import {toJS} from 'mobx';
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
import ShareDialog from '../dialog/shareDialog'
import ExchangeDialog from '../dialog/exchangeDialog'
import TaskInfoDialog from '../dialog/taskDialog'
import TaskCardNew from "../single/task/TaskCardNew";
import "./index.less";

@inject("taskPortalStore")
@observer
class TaskPortal extends React.Component {
    static contextTypes = {
        router: routerShape
    }
    constructor(props) {
        super(props);
        this.state = {
            current: 'allTask',
            ctrlHeight : 200,
            dialogVisiable : false,
            prjid : "",
            taskid : ""
        };

        const _this = this;
        window.openTaskPorTalCard = function (prjid,id) {
            _this.openTaskPorTalCard(prjid,id,true);
        }
    }
    componentDidMount() {
        const { taskPortalStore } = this.props;
        this.doInit(this.props);
        if (!window.weaWorkplan && !window.weaCowork) {
            eventRegister.loadModule('f_workplan', () => {
                eventRegister.loadModule('f_cowork', () => {
                    taskPortalStore.setLoaded(true)
                }, () => {
                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                    alert("加载协作模块失败，请联系系统管理员！");
                });
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载日程模块失败，请联系系统管理员！");
            });
            return;
        }
        if (window.weaWorkplan && !window.weaCowork) {
            eventRegister.loadModule('f_cowork', () => {
                taskPortalStore.setLoaded(true)
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载协作模块失败，请联系系统管理员！");
            });
        } else {
            eventRegister.loadModule('f_workplan', () => {
                taskPortalStore.setLoaded(true)
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载协作模块失败，请联系系统管理员！");
            });
        }

    }

    componentWillReceiveProps(nextProps){
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        if(keyOld !== keyNew) {
            const { taskPortalStore } = nextProps;
            taskPortalStore.clearStatus();
            taskPortalStore.taskGroupStore1.setId('allTask');
            this.setState({current: 'allTask'});
            this.doInit(this.props);
            if (!window.weaWorkplan && !window.weaCowork) {
                eventRegister.loadModule('f_workplan', () => {
                    eventRegister.loadModule('f_cowork', () => {
                        taskPortalStore.setLoaded(true)
                    }, () => {
                        // 加载文件失败 的业务处理， 网络超时，没文件之类
                        alert("加载协作模块失败，请联系系统管理员！");
                    });
                }, () => {
                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                    alert("加载日程模块失败，请联系系统管理员！");
                });
                return;
            }
            if (window.weaWorkplan && !window.weaCowork) {
                eventRegister.loadModule('f_cowork', () => {
                    taskPortalStore.setLoaded(true)
                }, () => {
                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                    alert("加载协作模块失败，请联系系统管理员！");
                });
            } else {
                eventRegister.loadModule('f_workplan', () => {
                    taskPortalStore.setLoaded(true)
                }, () => {
                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                    alert("加载协作模块失败，请联系系统管理员！");
                });
            }
        }
    }

    componentWillUnmount(){
        const { taskPortalStore } = this.props;
        taskPortalStore.clearStatus();
        taskPortalStore.taskGroupStore1.setId('allTask');
        this.setState({current: 'allTask'});
    }

    openTaskPorTalCard = (prjid,id,v) => {
        // console.log(id);
        this.setState({
            dialogVisiable : v,
            prjid : prjid,
            taskid : id ,
        })
    }

    doInit(props) {
        const { taskPortalStore } = props;
        const { initDatas, doSearch } = taskPortalStore;
        initDatas();
        doSearch({groupid:this.state.current});
    }
   
    render() {
        const { taskPortalStore } = this.props;
        const { title, groups, taskGroupStore, taskGroupStore1, tableStore, reLoad, loading , form ,  topTabCount, searchParams ,
             showSearchAd, exchangeStore, taskInfoStore, quickSearch, counts, searchValue, setSearchValue } = taskPortalStore;
        let topTab = [
            {
                color: '#000000',
                groupid: 'totalCount1',
                showcount: true,
                title: getLabel(332, "全部"),
                tabkey: "all"
            },
            {
                color: '#ff3232',
                groupid: 'totalCount2',
                showcount: true,
                title: getLabel(1979, "未开始"),
                tabkey: "todo"
            },
            {
                color: '#fea468',
                groupid: 'totalCount3',
                showcount: true,
                title: getLabel(1960, "进行中"),
                tabkey: "doing"
            },
            {
                color: '#9766fd',
                groupid: 'totalCount4',
                showcount: true,
                title: getLabel('21984', "已超期"),
                tabkey: "overtime"
            }
        ];
        const formParams = form.getFormParams() || {};
        const account = WeaTools.ls.getJSONObj('theme-account');
        let _this = this;
        return (
            <div className="prj-portal-page">
              
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@bigwxl`} title={getLabel('518195','任务门户')}  icon={<i className='icon-coms-project' />} buttons={[]} iconBgcolor='#217346' loading={loading}/>
                    <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@0ztfkl`}
                        leftWidth={300}
                        leftCom={
                            <div className="task-portal-left">
                                <div className="search-group" ref="searchGroup" style={{height:"100%"}}>
                                    <div className='quickSearch'>
                                        <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@cal3f5`}
                                            style={{width:"100%",padding:'2px'}}
                                            placeholder={getLabel('511884','搜索分组')}
                                            onSearch={quickSearch}
                                            value={searchValue}
                                            onChange={v =>{setSearchValue(v)}}
                                        />
                                    </div>
                                    {/* <br /> */}
                                    <div   style={{ width: '100%',paddingTop:'10px',height:"calc(100% - 20px)" }} >
                                        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@nk5gj4`}  height={"100%"} onScroll={(e)=>{ this.setState({ scrollTop:e.target.scrollTop, }) }}>
                                            
                                            <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@5vctx8`}
                                                theme={'light'}
                                                onClick={this.handleClick}
                                                style={{ width: '100%'}}
                                                defaultOpenKeys={['sub1']}
                                                selectedKeys={[this.state.current]}
                                                mode="inline"
                                                >
                                                <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_MenuItem@36um6v`} key="allTask">
                                                    <i className="icon-coms-Modular-o" />
                                                    <span>{getLabel('30889','全部任务')}</span>
                                                    <span style={{color:'rgb(197, 197, 197)',float:'right'}}>{counts.allTask}</span>
                                                </Menu.Item>
                                                {/* <Menu.Item key="createTask">
                                                    <i className="icon-coms-Collection" />
                                                <span>{getLabel('382485','我创建的任务')}</span>
                                                </Menu.Item> */}
                                                {/* <Menu.Item key="unFinishTask">
                                                    <i className="icon-coms-yonghu" />
                                                    <span>getLabel('382482','我负责的任务')</span>
                                                </Menu.Item>
                                                <Menu.Item key="finishTask">
                                                    <i className="icon-coms-File" />
                                                    <span>getLabel('518187','我管理的任务')</span>
                                                </Menu.Item> */}
                                                <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_MenuItem@i5ucmi`} key="excuedTask">
                                                    <i className="icon-coms-currency-Task" />
                                                    <span>{getLabel(33103, "任务执行")}</span>
                                                    <span style={{color:'rgb(197, 197, 197)',float:'right'}}>{counts.excuedTask}</span>
                                                </Menu.Item>
                                                {/* <Menu.Item key="delPrj">
                                                    <i className="icon-coms-delete" />
                                                    <span>回收站</span>
                                                </Menu.Item> */}
                                                <SubMenu ecId={`${this && this.props && this.props.ecId || ''}_SubMenu@im1lsx`}
                                                    key="sub1"
                                                    title={
                                                    <span>
                                                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@tqnbu6`} type="hdd" />
                                                        <span>{getLabel('518189','任务分组')}</span>
                                                        <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@9acc7h`} type="plus-square" className="add-icon" onClick={(e) =>{e.stopPropagation() ;taskGroupStore.handleTaskGroupDialog(true)}} />
                                                    </span>
                                                    }
                                                >
                                                    {this.getGroups(groups)}
                                                </SubMenu>
                                            </Menu>
                                        
                                        
                                        </WeaNewScroll>
                                    </div>
                                    <AddTaskGroupDialog ecId={`${this && this.props && this.props.ecId || ''}_AddTaskGroupDialog@y79zfj`} taskPortalStore={taskPortalStore} taskGroupStore={taskGroupStore} />
                                    <AddTaskGroupDialog ecId={`${this && this.props && this.props.ecId || ''}_AddTaskGroupDialog@c7mude`} taskPortalStore={taskPortalStore} taskGroupStore={taskGroupStore1} />
                                </div>   
                            </div>
                        }
                        onCollapse={showLeft => console.log('showLeft:', showLeft)}
                    >
                    <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@jcm536`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)} >
                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@sttb3k`}
                                datas={topTab}
                                counts={topTabCount}
                                keyParam="tabkey"  //主键
                                countParam="groupid" //数量
                                selectedKey={searchParams.tabkey}
                                buttonsAd={getAdButtons(taskPortalStore,this.props.ecId || '')}
                                searchType={['base', 'advanced']}
                                searchsBaseValue={formParams.taskname}
                                setShowSearchAd={bool => { taskPortalStore.setShowSearchAd(bool) }}
                                hideSearchAd={() => taskPortalStore.setShowSearchAd(false)}
                                searchsAd={
                                    <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@f7atl2`} listStore={taskPortalStore} form={form} onEnterSearch={this.onEnterSearch} ></Condition></div>
                                }
                                showSearchAd={showSearchAd}
                                onSearch={v => { taskPortalStore.doSearch() }}
                                onSearchChange={v => { taskPortalStore.setFormFields({ taskname: { value: v } }) }}
                                onChange={this.changeData}
                            />

                            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@q0fpt4`}
                                comsWeaTableStore={tableStore}
                                hasOrder={true}
                                needScroll={true}
                                register_table={() => reLoad()}
                                getColumns={c => this.reRenderColumns(c)}
                                tableWidth={this.tableWidth}
                                onOperatesClick={this.onOperatesClick.bind(this)}
                            />
                        </WeaRightMenu>
                </WeaLeftRightLayout>
                {window.weaCowork && window.weaCowork.com && window.weaCowork.com.CreateCowork && this.state.coWorkVisiable && this.state.taskid !== "" && (
                    <window.weaCowork.com.CreateCowork ecId={`${this && this.props && this.props.ecId || ''}_CreateCowork@wodj9h`}
                        initAddQuery={
                            {
                                relatedType: "task",
                                ids: this.state.taskid
                            }
                        }
                        onCancel={() => {
                            this.setState({
                                coWorkVisiable: false
                            });
                        }}
                    />)
                }
                {
                    taskPortalStore.isreloadWorkPlan && window.weaWorkplan && window.weaWorkplan.com && window.weaWorkplan.com.WorkPlanCreate &&
                    (<window.weaWorkplan.com.WorkPlanCreate ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@hk509w`}
                        type={"create"}//新建为'create',查看为'preview',编辑edit,共享share
                        visible={_this.state.workPlanVisible}//显隐受控
                        doClose={() => { _this.setWorkPlanVisible(false); }}//关闭回调
                        onlyClose={() => { _this.setWorkPlanVisible(false) }}//关闭回调,只做关闭操作
                        workPlanId={""} //日程id，1查看日程时用到
                        createConditionParams={[]}//创建的默认值日期和时间,没有传[]
                        activeKey={""} //查看页面显示的面板1是基本信息，7是相关交流
                        //changeTab={(key) => { }}//查看页面切换面板的回调
                        selectUser={account && account.userid}//新建日程的创建人id
                        workPlanTypeOptions={"2"}//客户模块的新建日程，普通新建传'',客户新建传3
                        projectid={_this.state.projectid}
                        taskid={_this.state.taskid}
                        description={""}//客户模块需求，支持新建时传入的'基本信息-内容'
                    />)
                }
                <ShareDialog ecId={`${this && this.props && this.props.ecId || ''}_ShareDialog@xj285x`} contentStore={taskPortalStore} />
                <ExchangeDialog ecId={`${this && this.props && this.props.ecId || ''}_ExchangeDialog@iawxl7`} contentStore={exchangeStore} />
                <TaskInfoDialog ecId={`${this && this.props && this.props.ecId || ''}_TaskInfoDialog@uarjck`} contentStore={taskInfoStore} />
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@rnatxo`}
                    onCancel={() => this.setState({ dialogVisiable: false })}
                    visible={this.state.dialogVisiable}
                    style={{ width: '65%', height: 648 }}
                >   
                { this.state.dialogVisiable && <TaskCardNew ecId={`${this && this.props && this.props.ecId || ''}_TaskCardNew@gn3t7z`} delCallBack={this.delCallBack} prjid={this.state.prjid} taskid={this.state.taskid} hasList={false} isDialog={true}/>}
                </WeaDialog>
            </div>
        )
    }

    onEnterSearch=() =>{
        const { taskPortalStore } = this.props;
        taskPortalStore.doSearch();
        taskPortalStore.setShowSearchAd(false);
    }

    setWorkPlanVisible = (bool) => {
        this.setState({ workPlanVisible: bool })
    }
    
    onScrollEnd = () => {
        const { searchNextPage } = this.props.taskPortalStore;
        searchNextPage();
    }

    tableWidth = (columns) => {
        let width = 0;
        let cols = 0;
        columns.map(col => {
          if (col.display === 'true') {
            let oldwidth = col.oldWidth || '10%';
            let widthInt = parseFloat(oldwidth.replace('%', ''));
            if (widthInt <= 0) {
              widthInt = 10;
            }
            width += widthInt;
            cols++
          }
        })
        //超过10列，才出现滚动条，width>100才出现滚动条
        if(cols<=10){
            width = 100 ;
        }
        return `${width}%`;
    }

    
    getRightMenu() {
        const { taskPortalStore } = this.props;
        const { rightMenu } = taskPortalStore;
        let btnArr = [];
        rightMenu && rightMenu.length > 0 && rightMenu.map(m => {
            btnArr.push({
                icon: <i className={m.menuIcon} />,
                content: m.menuName
            })
        });
        return btnArr
    }

    onRightMenuClick = (key)=>{
        const { taskPortalStore } = this.props;
        const { rightMenu } = taskPortalStore;
        let that = this;
        rightMenu && rightMenu.length > 0 && rightMenu.map((m, i) => {
            if (Number(key) == i) {
                let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
                if (m.type == "BTN_COLUMN") { //定制列
                    taskPortalStore.onShowColumn();
                }
            }
        });
    }

    reRenderColumns(columns){
        // console.log(columns,1111);
        columns.forEach((c,i)=>{
            if(c.dataIndex=='finish'){
                c.render = function(text, record){
                    return  <span  className='wea-prj-progressStyle' >
                    <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@8p33yw@${i}`} percent={record.finish}  strokeColor={record.finishspan} />
                </span>
                }
            } else {
              c.render = function(text, record){
                  let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                  return <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
                }
            }
        })
        return columns;
    }

    handleClick = e => {
        const {taskPortalStore} = this.props;
        taskPortalStore.doSearch({groupid:e.key});
        taskPortalStore.taskGroupStore1.setId(e.key);
        this.setState({
          current: e.key,
        });
    };

    changeScope = (viewScope) => {
        this.setState({viewScope : viewScope})
    }

    getGroups = (arr) =>{
        const { taskPortalStore } = this.props;
        const { deleteTaskGroupInfo,taskGroupStore1 } = taskPortalStore;
        let datas = [];
        arr.map(c =>{
            datas.push(<Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_MenuItem@fjitun@${c.id}`} key={c.id} >{c.name}
            <i className='icon-coms-delete' style={{float:'right',paddingTop:'15px'}} onClick={(e) =>{
                e.stopPropagation();
                e.preventDefault();
                deleteTaskGroupInfo({groupid:c.id});
                if(this.state.current==c.id){
                    this.setState({current:'allTask'});
                }
            }} />
            <i className='icon-coms-edit' style={{float:'right',paddingTop:'15px'}} onClick={(e) =>{
                e.stopPropagation();
                e.preventDefault();
                taskGroupStore1.handleTaskGroupDialog(true,{id:c.id});
            }} />
            </Menu.Item>);
        })
        return datas;
    }

    forwardProjectCard(query){
        const path = "/portal/card"+query;
        this.context.router.push({
            pathname: "/main/prj"+path
        });
    }

    onOperatesClick(record, index, operate, flag) {
        const { taskPortalStore: { shareStore, exchangeStore, taskInfoStore } } = this.props;
        let _href = operate && operate.href ? operate.href : "";
        let fn = _href.replace("javascript:", "");
        fn = fn.substring(0, fn.indexOf('('));
        let that = this;
        if (fn != "") {
            if ("onShare" == fn) {  //共享
                shareStore.handleShareDialog(true, "task", record.randomFieldId, {})
            } else if ('onNewCowork' == fn) {   //新建协作
                this.setState({ coWorkVisiable: true, taskid: record.randomFieldId, projectid: record.prjid })
                const coworkStoreMap = window.weaCowork.store && window.weaCowork.store.coworkStoreMap;
                const cowortore = coworkStoreMap && coworkStoreMap.getMapStore(3);
                cowortore && cowortore.setCreateState({ showNewCowork: true, createOrEdit: 0 });
            } else if ('onNewWorkplan' == fn) {   //新建日程
                this.setState({ workPlanVisible: true, taskid: record.randomFieldId, projectid: record.prjid })
            } else if ('onApprove' == fn) {   //

            } else if ('onReject' == fn) {   //

            } else if ('onEdit' == fn) {   //编辑
                taskInfoStore.handleDialog(true, "edit", record.randomFieldId);
            } else if ('onDiscuss' == fn) {   //相关交流
                exchangeStore.handleExchangeDialog(true, "task", record.randomFieldId, {})
            } else if ('onDel' == fn) {   //删除
                taskInfoStore.delTask("del", record.randomFieldId);
            }
        }
    }

    changeData = (key) => {
        const { taskPortalStore } = this.props;
        taskPortalStore.setShowSearchAd(false);
        taskPortalStore.doSearch({
            tabkey: key
        });
    }

    delCallBack = () => {
        const { taskPortalStore } = this.props;
        const { initDatas, doSearch } = taskPortalStore;
        this.setState({dialogVisiable:false});
        initDatas();
        doSearch({groupid:this.state.current});
    }

}

export default TaskPortal;